package com.dragon8869.myspringboot.service.user;

import com.dragon8869.myspringboot.entity.AyRole;
import com.dragon8869.myspringboot.entity.AyUser;
import com.dragon8869.myspringboot.entity.AyUserRoleRel;
import com.dragon8869.myspringboot.service.AyRoleService;
import com.dragon8869.myspringboot.service.AyUserRoleRelService;
import com.dragon8869.myspringboot.service.AyUserService;
import com.google.common.collect.Lists;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.List;

public class CustomUserService implements UserDetailsService {

    @Resource
    private AyUserService ayUserService;
    @Resource
    private AyUserRoleRelService ayUserRoleRelService;
    @Resource
    private AyRoleService ayRoleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        AyUser ayUser = ayUserService.findByName(username);
        Assert.notNull(ayUser, "用户不存在");
        List<GrantedAuthority> grantedAuthorityList = Lists.newArrayList();
        List<AyUserRoleRel> ayUserRoleRelList = ayUserRoleRelService.findByUserId(ayUser.getId());
        ayUserRoleRelList.forEach(ayUserRoleRel -> {
            AyRole ayRole = ayRoleService.find(ayUserRoleRel.getRoleId());
            Assert.notNull(ayRole, "不存在的角色");
            grantedAuthorityList.add(new SimpleGrantedAuthority(ayRole.getName()));
        });
        return new User(ayUser.getName(), ayUser.getPassword(), grantedAuthorityList);
    }
}
